package cn.zxone.feishu.demo.controller;

import cn.zxone.feishu.demo.common.config.FeiShuClientManager;
import cn.zxone.feishu.demo.common.exception.CustomException;
import cn.zxone.feishu.demo.common.pojo.Result;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/feishu")
public class FeiShuController {


    @Resource
    private FeiShuClientManager feiShuClientManager;


    @GetMapping(value = "sendMsg")
    public Result<?> sendMsg(@RequestParam("msg") String msg) {


        Client client = feiShuClientManager.getClientByAlias("TEST");

        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("user_id")
                .createMessageReqBody(
                        CreateMessageReqBody.newBuilder()
                        .receiveId("9b48e657")
                        .msgType("text")
                        .content("{\"text\":\""+msg+"\"}")
                        .uuid(UUID.randomUUID().toString())
                        .build()
                )
                .build();

        CreateMessageResp resp = null;

        // 发起请求
        try {
            resp = client.im().v1().message().create(req);

            if (!resp.success()) {
                log.warn("发送飞书消息错误 code: {}, msg: {}, reqId: {}", resp.getCode(), resp.getMsg(), resp.getRequestId());
                throw new CustomException("发送飞书消息错误，" + resp.getMsg());
            }

        } catch (Exception e) {
            throw new CustomException("发送飞书消息失败", e);
        }

        return Result.success(resp.getData());
    }

}
